package cn.seocoo.platform.car.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.seocoo.platform.base.domain.BaseBrand;
import cn.seocoo.platform.base.domain.BaseVehicleType;
import cn.seocoo.platform.base.mapper.BaseBrandMapper;
import cn.seocoo.platform.base.mapper.BaseVehicleTypeMapper;
import cn.seocoo.platform.car.dto.CarDetailDto;
import cn.seocoo.platform.car.dto.CarDto;
import cn.seocoo.platform.car.dto.CarFrom;
import cn.seocoo.platform.common.constant.ClassContants;
import cn.seocoo.platform.common.utils.AmountUtils;
import cn.seocoo.platform.common.utils.StringUtils;
import cn.seocoo.platform.contrast.domain.CarBrowse;
import cn.seocoo.platform.contrast.mapper.CarBrowseMapper;
import cn.seocoo.platform.search.domain.SearchRecord;
import cn.seocoo.platform.search.mapper.SearchRecordMapper;
import cn.seocoo.platform.user.domain.AppUser;
import cn.seocoo.platform.user.mapper.AppUserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.netty.util.internal.UnstableApi;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.seocoo.platform.car.mapper.CarInfoMapper;
import cn.seocoo.platform.car.domain.CarInfo;
import cn.seocoo.platform.car.service.ICarInfoService;
import cn.seocoo.platform.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 车辆基本 服务层实现
 * 
 * @author wujian
 * @date 2019-12-31
 */
@Service
public class CarInfoServiceImpl implements ICarInfoService 
{
	@Autowired
	private CarInfoMapper carInfoMapper;
	@Autowired
	private BaseVehicleTypeMapper baseVehicleTypeMapper;
	@Autowired
	private SearchRecordMapper searchRecordMapper;
	@Autowired
	private AppUserMapper appUserMapper;
	@Autowired
	private BaseBrandMapper baseBrandMapper;
	@Autowired
	private CarBrowseMapper carBrowseMapper;

	/**
     * 查询车辆基本信息
     * 
     * @param id 车辆基本ID
     * @return 车辆基本信息
     */
    @Override
	public CarInfo selectCarInfoById(Integer id)
	{
	    return carInfoMapper.selectCarInfoById(id);
	}
	
	/**
     * 查询车辆基本列表
     * 
     * @param carInfo 车辆基本信息
     * @return 车辆基本集合
     */
	@Override
	public List<CarInfo> selectCarInfoList(CarInfo carInfo)
	{
	    return carInfoMapper.selectCarInfoList(carInfo);
	}
	
    /**
     * 新增车辆基本
     * 
     * @param carInfo 车辆基本信息
     * @return 结果
     */
	@Override
	public int insertCarInfo(CarInfo carInfo)
	{
	    return carInfoMapper.insertCarInfo(carInfo);
	}
	
	/**
     * 修改车辆基本
     * 
     * @param carInfo 车辆基本信息
     * @return 结果
     */
	@Override
	public int updateCarInfo(CarInfo carInfo)
	{
	    return carInfoMapper.updateCarInfo(carInfo);
	}

	/**
     * 删除车辆基本对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteCarInfoByIds(String ids)
	{
		return carInfoMapper.deleteCarInfoByIds(Convert.toStrArray(ids));
	}

	/**
	 * @Author WuJian
	 * @Description //查询用户发不了多少量车
	 * @Date 11:44 2019/12/31
	 * @Param [id]
	 * @return int
	 **/
	@Override
	public int getCountCarWithAppUserId(Integer appUserId) {
		return carInfoMapper.getCountCarWithAppUserId(appUserId);
	}


	/**
	 * @Author WuJian
	 * @Description //发布车辆
	 * @Date 11:55 2019/12/31
	 * @Param [carFrom]
	 * @return void
	 **/
	@Override
	public Map<String,String> publishCar(CarFrom carFrom) {
		Map<String,String> map = new HashMap<>();
		CarInfo carInfo = new CarInfo();
		BeanUtils.copyProperties(carFrom,carInfo);
		carInfo.setShelfStatus(CarInfo.SHELF);
		carInfo.setCreateTime(new Date());
		String amount = AmountUtils.changeY2F(carFrom.getIntentionAmount());
		carInfo.setIntentionAmount(Integer.valueOf(amount));
		//正常直接发布
		if(CarInfo.PUBLISH_TYPE.equals(carFrom.getPublishType())){
			carInfo.setDelFlag(ClassContants.NO_DEL_FLAG);
			carInfo.setIsTop(CarInfo.NO_TOP);
			carInfoMapper.insertCarInfo(carInfo);
			map.put("name","3");
			map.put("value","发布成功");

			//置顶发布
		}else if(CarInfo.TOP_PUBLISH_TYPE.equals(carFrom.getPublishType())){
			carInfo.setDelFlag(ClassContants.IS_DEL_FLAG);
			carInfoMapper.insertCarInfo(carInfo);
			//创建置顶订单



			return map;
		}
		return map;
	}


	/**
	 * @Author WuJian
	 * @Description //首页标题筛选
	 * @Date 15:53 2019/12/31
	 * @Param [title]
	 * @return java.util.List<cn.seocoo.platform.car.dto.CarDto>
	 **/
	@Override
	@Transactional(rollbackFor = Exception.class)
	public List<CarDto> getCarList(String title,Integer pageNum,Integer pageSize,Integer appUserId) {
		//插入到搜索记录中
		if(StringUtils.isNotBlank(title)){
			SearchRecord sr = searchRecordMapper.selectSearchRecordByTitle(title,appUserId);
			if(sr != null){
				sr.setCreateTime(new Date());
				searchRecordMapper.updateSearchRecord(sr);
			}else{
				SearchRecord searchRecord = new SearchRecord();
				searchRecord.setDelFlag(ClassContants.NO_DEL_FLAG);
				searchRecord.setSearchTitle(title);
				searchRecord.setAppUserId(appUserId);
				searchRecord.setCreateTime(new Date());
				searchRecordMapper.insertSearchRecord(searchRecord);
			}
		}
		//开启分页
		PageHelper.startPage(pageNum == null? 1:pageNum,pageSize == null?10:pageSize);
		List<CarDto> carDtoList = carInfoMapper.getCarList(title);


		return carDtoList;
	}

    /**
     * @Author WuJian
     * @Description //查询车辆详情
     * @Date 10:34 2020/1/2
     * @Param [id]
     * @return cn.seocoo.platform.car.dto.CarDetailDto
     **/
    @Override
	@Transactional(rollbackFor =Exception.class)
    public CarDetailDto getCarDetail(Integer id,Integer appUserId) throws Exception{
        CarDetailDto carDetailDto =carInfoMapper.getCarDetail(id);
        if(carDetailDto != null){
			//查询当前用户了解的车辆信息,是否已经存在
			CarBrowse cb = carBrowseMapper.selectCarBrowseByAppUserIdAndCarId(id,appUserId);
			if(cb != null){
				cb.setCreateTime(new Date());
				carBrowseMapper.updateCarBrowse(cb);
			}else{
				//将当前用户查询到的车辆和用户添加到浏览记录中去
				CarBrowse carBrowse = new CarBrowse();
				carBrowse.setAppUserId(appUserId);
				carBrowse.setCarInfoId(id);
				carBrowse.setDelFlag(ClassContants.NO_DEL_FLAG);
				carBrowseMapper.insertCarBrowse(carBrowse);
			}

            if(!AppUser.BUSINESSES_USER.equals(carDetailDto.getUserType())){
                CarInfo carInfo = carInfoMapper.selectCarInfoById(id);
                carDetailDto.setName(carInfo.getContacts());
            }else{
                Integer userId = carDetailDto.getUserId();
                AppUser appUser = appUserMapper.selectAppUserById(userId);
                carDetailDto.setName(appUser.getUnitName());
                carDetailDto.setContent(appUser.getUnitContent());
            }

            if (StringUtils.isNotBlank(carDetailDto.getBaseCarriageSize())) {
                Integer vehicleId = carDetailDto.getVehicleId();
                BaseVehicleType baseVehicleType = baseVehicleTypeMapper.selectBaseVehicleTypeById(vehicleId);
                carDetailDto.setBaseCarriageSize(carDetailDto.getBaseCarriageSize() + baseVehicleType.getDimension());
            }

            if (StringUtils.isNotBlank(carDetailDto.getAmount())) {
                carDetailDto.setAmount(AmountUtils.changeF2W(carDetailDto.getAmount()) + "万");
            }
            //如果车辆品牌存放的是不限
            if(carDetailDto.getBrandId() != null){
                if(BaseBrand.BRAND_NAME.equals(carDetailDto.getBaseBrandName())){
                    BaseBrand baseBrand = baseBrandMapper.selectBaseBrandById(carDetailDto.getBrandId());
                    if(baseBrand != null){
                        BaseBrand parentBrand =  baseBrandMapper.selectBaseBrandById(baseBrand.getParentId());
                        carDetailDto.setBaseBrandName(parentBrand.getBrandName());
                    }
                }
            }
            if(StringUtils.isNotBlank(carDetailDto.getBasePaymentType())){
                /** 过户类型(1:可提档;2:包提档;3需挂靠) */
                if(CarInfo.ONE_TRANSFER_TYPE.equals(carDetailDto.getBasePaymentType())){
                    carDetailDto.setBaseTransferType("可提档");
                }else if(CarInfo.TWO_TRANSFER_TYPE.equals(carDetailDto.getBasePaymentType())){
                    carDetailDto.setBaseTransferType("包提档");
                }else if(CarInfo.THREE_TRANSFER_TYPE.equals(carDetailDto.getBasePaymentType())){
                    carDetailDto.setBaseTransferType("3需挂靠");
                }
            }

            if(StringUtils.isNotBlank(carDetailDto.getBasePaymentType())){
                /** 付款方式(1:全款;2:;3需挂靠) */
                if(CarInfo.ONE_PAY_MENT_TYPE.equals(carDetailDto.getBasePaymentType())){
                    carDetailDto.setBasePaymentType("全款");
                }else if(CarInfo.TWO_PAY_MENT_TYPE.equals(carDetailDto.getBasePaymentType())){
                    carDetailDto.setBaseTransferType("贷款");
                }else if(CarInfo.THREE_PAY_MENT_TYPE.equals(carDetailDto.getBasePaymentType())){
                    carDetailDto.setBaseTransferType("半全款");
                }
            }

        }
        return carDetailDto;
    }

    /**
     * @Author WuJian
     * @Description //车辆上下架
     * @Date 14:39 2020/1/3
     * @Param [id, shelfStatus]
     * @return int
     **/
	@Override
	public int shelfCar(Integer id, String shelfStatus) {
		CarInfo carInfo = new CarInfo();
		carInfo.setId(id);
		carInfo.setShelfStatus(shelfStatus);
		int row = carInfoMapper.updateCarInfo(carInfo);
		return row;
	}

}
